<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/4/3
 * Time: 21:19
 */

namespace App\Services;


use App\Models\GoldShop;
use App\Models\Member;
use App\Models\UserGoldLog;
use App\Models\UserLotteryLog;
use App\Repos\MemberRepo;
use Illuminate\Support\Facades\DB;

class GoldShopService
{
    protected $memberRepo;
    public function __construct(MemberRepo $memberRepo)
    {
        $this->memberRepo=$memberRepo;
    }
    
    /**
     * 获取金币小铺的所有数据列表
     * @return mixed
     */
    public function goldShopList(){
        $list = GoldShop::all();
        $array = array();
        foreach($list as $d){
            $value['id'] = $d['GoldShopID'];
            $value['golds'] = $d['GoldCoin'];
            $value['score'] = $d['Integral'];
            $array[] = $value;
        }
        return $array;
    }

    /**
     * 抽取金币小铺的某个积分
     * @param $user_id
     * @param $user_golds
     * @param $lottery_id
     * @return array
     */
    public function lottery($user_id,$user_golds,$lottery_id){
        //获取抽奖信息
        $lottery = GoldShop::where('GoldShopID',$lottery_id)->first();
        if(!$lottery) return ['result'=>false,'tip'=>'您所参与的抽奖不存在！'];
        if($user_golds < $lottery['GoldCoin']){
            //用户金币数量不足
            return ['result'=>false,'tip'=>'您的金币数量不足！'];
        }
        //判断是否获取到了积分
        $getPrize = $this->calInPrize($lottery['WinningPercentage']/100.0,$lottery['JoinNum']);
        //扣减金币
        Member::where('uid',$user_id)->decrement('P_credit',$lottery['GoldCoin']);
        $userGoldLog = new UserGoldLog();
        $userGoldLog->setAttribute("user_id",$user_id);
        $userGoldLog->setAttribute("operate",-1);
        $userGoldLog->setAttribute("gold_num",$lottery['GoldCoin']);
        $userGoldLog->setAttribute("descr",'金币抽积分');
        $userGoldLog->save();
        $userLotteryLog = new UserLotteryLog();
        $userLotteryLog->setAttribute("user_id",$user_id);
        $userLotteryLog->setAttribute("lottery_id",$lottery_id);
        $userLotteryLog->setAttribute("gold_num",$lottery['GoldCoin']);
        $userLotteryLog->save();
        if($getPrize){

            $this->memberRepo->incrementUserRemoteScore(Member::find($user_id),$lottery['Integral']);
            return ['result'=>true,'tip'=>'恭喜您抽中'.$lottery['Integral'].'积分！'];
        }
        return ['result'=>false,'tip'=>'很抱歉，您本次抽奖未中奖！'];

    }
    private function calInPrize($winningPercentage,$joinNum){
        $randomNumber = mt_rand(0,$joinNum);
        if($randomNumber>0 && $randomNumber<$joinNum*$winningPercentage){
            return true;
        }
        return false;
    }


}